#include "mutigame.h"

MutiGame::MutiGame()
{

}


void MutiGame::init(Transiver *transiver)
{
    timer = new QTimer;
    this->transiver = transiver;


    /* set background music */
    sound = new QSoundEffect(this);
    sound->setSource(QUrl::fromLocalFile(":/bgm/Grazy Dave.wav"));
    sound->setLoopCount(QSoundEffect::Infinite);
    sound->setVolume(0.5);
    sound->play();

    /* set scene */
    scene = new QGraphicsScene(this);
    scene->setSceneRect(150, 0, 900, 600);
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);

    /* set shop */
    Shop *shop;
    if(faction == Zombie)
    {
        shop = new ZombieShop();

    }else
    {
        shop = new PlantShop();
    }
    shop->setPos(520, 45);
    scene->addItem(shop);



    Shovel *shovel = new Shovel;
    shovel->setPos(830, 40);
    scene->addItem(shovel);

    Button *button = new Button(sound, timer);
    button->setPos(970, 20);
    scene->addItem(button);
    connect(button, SIGNAL(itemClicked()), transiver, SLOT(sendStopMsg()));
    connect(transiver, SIGNAL(GameStop()), button, SLOT(PressEvent()));


    Map *map = new Map(transiver);
    map->setPos(618, 326);
    scene->addItem(map);
    for (int i = 0; i < 5; ++i)
    {
        Mower *mower = new Mower;
        mower->setPos(210, 130 + 98 * i);
        scene->addItem(mower);
    }

    view = new QGraphicsView(scene, this);
    view->resize(902, 602);
    view->setRenderHint(QPainter::Antialiasing);
    view->setBackgroundBrush(QPixmap(":/images/Background.jpg"));
    view->setCacheMode(QGraphicsView::CacheBackground);
    view->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);


    timer->start(33);
    view->show();

    connect(timer, &QTimer::timeout, scene, &QGraphicsScene::advance);
    connect(transiver, SIGNAL(broadCast(int,int,int,QString)), shop, SLOT(addPlant(int,int,int,QString)));

    //    connect(timer, &QTimer::timeout, this, &MainWindow::addZombie);
    connect(timer, &QTimer::timeout, this, &MutiGame::check);
}


void MutiGame::check()
{
    static int time = 1 * 1000 / 33;
    static int counter = 0;
    if (++counter >= time)
    {
        counter = 0;
        const QList<QGraphicsItem *> items = scene->items();
        foreach (QGraphicsItem *item, items)
            if (item->type() == Zombie::Type && item->x() < 200)
            {
                scene->addPixmap(QPixmap(":/images/ZombiesWon.png"))->setPos(336, 92);
                scene->advance();
                timer->stop();
                return;
            }
    }
}
void MutiGame::setFaction(Faction _faction)
{
    this->faction = _faction;
}


MutiGame::Faction MutiGame::getFaction()
{
    return faction;
}
